<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="email"
          left-icon="notes"
          name="email"
          label="邮箱"
          placeholder="请填写邮箱"
          type="tel"
          size="large"
          clearable
      />
      <van-field
          v-model="userCode"
          center
          type="digit"
          left-icon="setting"
          name="userPassword"
          label="验证码"
          placeholder="请填写验证码"
          size="large"
          style="margin-top: 1vh"
          clearable
      >
        <template #button>
          <van-button style="margin-left: 1vw" v-if="!countdown" @click="sendCode" size="small" type="primary">发送验证码</van-button>
          <van-button v-else size="small">{{ remainingTime }}s</van-button>
        </template>
      </van-field>
    </van-cell-group>


    <div style="margin-top: 10vh;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
</template>


<script setup>
import { ref} from "vue";
import {showToast} from "vant";
import {emailLoginAPI, emailToCodeAPI} from "../../api/email/email.js";

import { useTabbarStore } from '../../stores/tabbar';
import {useUserStore} from "../../stores/user.js";
import {useRouter} from "vue-router";
const userStoreAPI = useUserStore();
const tabbarStore = useTabbarStore();
const router = useRouter();
const email = ref('');
const userCode = ref('');
const countdown = ref(false);
const remainingTime = ref(60);



const onSubmit = async() => {
  //校验参数
  const qqEmailRegex = /^[1-9]\d{4,}@qq\.com$/;
  if (!qqEmailRegex.test(email.value)){
    showToast("邮箱不正确");
    return;
  }

  if (userCode.value === ''){
    showToast("请填写验证码");
    return;
  }

  const data = {
    email: email.value,
    code: userCode.value
  };

  //调用登录接口
   //调用登录接口
  const res = await emailLoginAPI(data);
  if(res.success){
    showToast("登录成功");
    const userInfo = res.data;
    //保存用户信息到本地
    // localStorage.setItem("userInfo", JSON.stringify(userInfo));

    userStoreAPI.setLoginInfo(userInfo,'');
    //跳转到首页
    tabbarStore.setActive('home');
    router.push("/");
  }else{
  }
};



//发送验证码方法
const sendCode = async ()=>{
  //不能一直发送
  if (remainingTime.value!=60){
    return;
  }

  //校验
  if (email.value == ''){
    showToast("请填写邮箱");
    return;
  }
  //邮箱的正则校验
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!emailReg.test(email.value)){
    showToast("邮箱不正确");
    return;
  }

  //调用接口发验证码，倒计时60秒
  const res = await emailToCodeAPI(email.value);
  if(res.success){
    showToast("验证码发送成功");
    countdown.value = true;
    const timer = setInterval(() => {
      if (remainingTime.value > 0) {
        remainingTime.value--;
      } else {
        clearInterval(timer);
        countdown.value = false;
        remainingTime.value = 60;
      }
    }, 1000);
  }
};


</script>



<style scoped>

</style>